<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <base href="<%=request.getContextPath()%>/"/>
</head>
<body>
<button onclick="send()">send</button>
<script src="js/jquery-2.1.4.js"></script>
<script src="js/websocket/websocket.js"></script>
<script type="text/javascript">
    var principal = 'public';
    //var socketURL = 'ws://localhost:8081/study/websocket/' + principal;
     console.log(window.location.host)
     var socketURL = 'ws://' + window.location.host
        + '/study/websocket/' + principal;

    websocket = $.websocket(socketURL, {
        open : function() {
            // when the socket opens
            console.info("open");
        },
        close : function() {
            // when the socket closes
            console.info("close");
        },
        //收到服务端推送的消息处理
        events : {
            'radio' : function(event) {
                console.info($.parseJSON(event.data));
            },
            'notice' : function(event) {
                console.info($.parseJSON(event.data));
            },
            //... more custom type of message
        }
    });

    // 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常.
    window.onbeforeunload = function() {
        websocket.close();
    }

    // 监听浏览器回退事件
    window.onpagehide = function(event) {
        websocket.close();
    }

    //发送消息
    function send() {
        websocket.send('radio', " hello,this msg from client request");
    }
</script>
</body>
</html>